module.exports = (app, router) => {
    const comment = require('../../models/comment')
    const count = require('../../models/counts')
    const { requestResult, pagingResult } = require('../../plugins/index')

    router.post('/comment', async (req, res) => {
        const page = Number(req.body.page) || 1
        const size = Number(req.body.size) || 10
        let data = pagingResult(comment, page, size)
        res.send(requestResult(data))
    })

    router.post('/addComment', async (req, res) => {
        const commentId = await count.findOneAndUpdate({ name: 'commentId' }, { $inc: { 'id': 1 }}, { new: true})
        if(commentId){
            req.body.id = commentId
        }else{
            const info = {
                name: 'commentId',
                id: 1
            }
            const i = await count.create(info)
            req.body.id = i.id
        }
        const result = comment.create(req.body)
        res.send(requestResult(result))
    })

    router.delete('removeComment', async (req, res) => {
        const id = req.body.id
        const pro = [
            new Promise((resove, reject) => {
                comment.deleteOne({ id }, (err, item) => item ? resove(item) : reject())
            })
        ]
        if(!req.body.parentId){
            pro.push(new Promise((resove, reject) => {
                comment.deleteMany({ parentId: req.body.parentId}, (err, item) => item ? resove(item) : reject())
            }))
        }

        Promise.all(pro).then(item => {
            res.send(requestResult(item[0]))
        }).catch(e => {
            res.send(requestResult())
        })
    })

    app.use('/admin/api', router)
}